package com.nantian.logic.controller;

import com.cuit.springboot.gdao.common.ArticleHtmlMapper;
import com.cuit.springboot.gdao.support.ApplySupportMapper;
import com.cuit.springboot.gdao.support.BusinessSupportMapper;
import com.cuit.springboot.gentry.common.ArticleHtml;
import com.cuit.springboot.gentry.support.ApplySupport;
import com.cuit.springboot.gentry.support.BusinessSupport;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nantian.logic.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by AileYoung on 2018/2/5.
 */
@RestController
@RequestMapping(value = "/business")
public class BusinessSupportController {
    @Autowired
    BusinessSupportMapper businessSupportMapper;
    @Autowired
    ApplySupportMapper applySupportMapper;
    @Autowired
    ArticleHtmlMapper articleHtmlMapper;
    @Autowired
    TokenUtil tokenUtil;

    /**
     * 获取全部赞助列表
     */
    @PostMapping(value = "selectList")
    public UniversalResult<PageInfo<BusinessSupport>> selectList(@RequestBody Map<String, Integer> map) {
        PageHelper.startPage(map.get("pageNo"), map.get("pageSize"));
        PageInfo<BusinessSupport> page = new PageInfo<>(businessSupportMapper.selectAll());
        if (page.getSize() > 0)
            return new UniversalResult<>(UniversalResult.SUCCESS, "查询成功", page);
        else
            return new UniversalResult<>(UniversalResult.GETNULL, "空空如也");
    }

    /**
     * “发起赞助”接口
     * 需要参数：赞助实体
     */
    @PostMapping(value = "/publish")
    public UniversalResult startSup(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        String userId = tokenUtil.getUserId(request);
        if (StringUtils.isBlank(userId))
            return new UniversalResult(UniversalResult.UNLOGIN, "登录信息失效，请重新登录");

        ArticleHtml articleHtml = new ArticleHtml();
        articleHtml.setContent(map.get("supDetail") == null ? "null" : map.get("supDetail").toString());
        articleHtml.setArticleId(uuidGenerate.generate());
        articleHtml.setUploadtime(DateUtils.getDateTime());
        articleHtml.setDel(Byte.valueOf("0"));
        articleHtml.setEnabled(Byte.valueOf("0"));
        articleHtml.setType(Byte.valueOf("2"));
        articleHtml.setUserid(userId);
        articleHtmlMapper.insert(articleHtml);

        map.put("userId", userId);
        map.put("detailId", articleHtml.getArticleId());
        map.put("del", (byte) 0);
        businessSupportMapper.insertMap(map);
        return new UniversalResult(UniversalResult.SUCCESS, "发起赞助成功");
    }

    /**
     * “我发布的赞助”接口
     * 需要参数：查询者id（userId）
     */
    @PostMapping(value = "/mySup")
    public UniversalResult<List<BusinessSupport>> mySup(@RequestBody BusinessSupport BS) {
        List<BusinessSupport> mySupList = new ArrayList<>();
        if (mySupList.size() > 0) {
            return new UniversalResult<>(UniversalResult.SUCCESS, "查询成功", mySupList);
        } else
            return new UniversalResult<>(UniversalResult.GETNULL, "空空如也");
    }

    /**
     * “我的合作”查询接口
     * 需要参数：查询者id（userId）
     */
//    @PostMapping(value = "/together")
//    public UniversalResult<List<TogetherEntity>> together(@RequestBody Toge together) {
//        List<TogetherEntity> togetherList = new ArrayList<>();
//
//        //获得Aid列表，再从活动表中查询活动信息返回
//
//        return new UniversalResult<>(UniversalResult.SUCCESS, "查询成功", togetherList);
//    }

    /**
     * “赞助详情”查询接口
     * 需要参数：赞助id（bsId）
     */
    @PostMapping(value = "selectInfo")
    public UniversalResult<Map<String, Object>> selectInfo(@RequestBody Map<String, Integer> map) {
        if (!map.containsKey("id") && StringUtils.isBlank(String.valueOf(map.get("id"))))
            return new UniversalResult<>(UniversalResult.GETNULL, "赞助id不能为空");
        else {
            int id = map.get("id");
            Map<String, Object> supInfo = businessSupportMapper.selectSupInfo(id);
            if (supInfo == null)
                return new UniversalResult<>(UniversalResult.GETNULL, "您要查询的赞助不见啦");
            Map<String, Object> article = new HashMap<>();
            Map<String, Object> business = new HashMap<>();

            MapUtils.moveMapValue(supInfo, article, "articleId");
            MapUtils.moveMapValue(supInfo, article, "articleType");
            MapUtils.moveMapValue(supInfo, article, "uploadTime");
            MapUtils.moveMapValue(supInfo, article, "enabled");
            MapUtils.moveMapValue(supInfo, article, "content");
            supInfo.put("article", article);
            MapUtils.moveMapValue(supInfo, business, "businessUserId");
            MapUtils.moveMapValue(supInfo, business, "email");
            MapUtils.moveMapValue(supInfo, business, "realName");
            MapUtils.moveMapValue(supInfo, business, "sex");
            MapUtils.moveMapValue(supInfo, business, "qq");
            MapUtils.moveMapValue(supInfo, business, "authForView");
            MapUtils.moveMapValue(supInfo, business, "businessName");
            MapUtils.moveMapValue(supInfo, business, "cityId");
            MapUtils.moveMapValue(supInfo, business, "addr");
            MapUtils.moveMapValue(supInfo, business, "busiLevel");
            MapUtils.moveMapValue(supInfo, business, "busiScale");
            MapUtils.moveMapValue(supInfo, business, "introduce");
            MapUtils.moveMapValue(supInfo, business, "position");
            supInfo.put("business", business);
            supInfo.put("applicant", applySupportMapper.selectByBSId(id));
            return new UniversalResult<>(UniversalResult.SUCCESS, "查询成功", supInfo);
        }
    }

    /**
     * 根据bId查询其全部赞助
     * 所需参数:分页参数和bId
     * */
    @PostMapping(value = "selectWhoseList")
    public UniversalResult<PageInfo<Map<String,Object>>> selectWhoseList(@RequestBody Map<String, Object> map) {
        if (MapUtils.checkKeyIsNull(map,"pageNo","pageSize","bId"))
            return new UniversalResult<>(UniversalResult.GETNULL, "参数不能为空");
        else {
            PageHelper.startPage((int)map.get("pageNo"), (int)map.get("pageSize"));
            PageInfo<Map<String,Object>> page = new PageInfo<>(businessSupportMapper.selectWhoseList(map.get("bId").toString()));
            if (page.getList().size() > 0)
                return new UniversalResult<>(UniversalResult.SUCCESS, "查询成功", page);
            else
                return new UniversalResult<>(UniversalResult.GETNULL, "空空如也");
        }
    }

    /**
     * “申请赞助”接口
     * 需要参数：申请者id（sId）、赞助id（bsId）
     */
    @PostMapping(value = "/applySup")
    public UniversalResult<Object> applySup(@RequestBody ApplySupport AS, HttpServletRequest request) {
        String sId = tokenUtil.getUserId(request);
        if (StringUtils.isBlank(sId))
            return new UniversalResult<>(UniversalResult.UNLOGIN, "登录信息失效，请重新登陆");
        if (applySupportMapper.selectMapBy(
                MapUtils.setSelectStatement("id", "SId=" + sId + " BSId=" + AS.getBsid())) != null)
            return new UniversalResult<>(UniversalResult.FAILURE, "您已经申请过该赞助了");
        BusinessSupport BS = businessSupportMapper.selectByPrimaryKey(AS.getBsid());
        if (BS != null) {
            AS.setStatus((byte) 0);
            AS.setDate(DateUtils.getDateTime());
            AS.setDel((byte) 0);
            applySupportMapper.insert(AS);
            return new UniversalResult<>(UniversalResult.SUCCESS, "申请成功");
        } else
            return new UniversalResult<>(UniversalResult.GETNULL, "您要申请的赞助不见啦");
    }

    /**
     * “我的赞助申请”查询接口
     * 需要参数：查询者id（sId）
     */
    @PostMapping(value = "myApply")
    public UniversalResult myApply(HttpServletRequest request) {
        String sId = tokenUtil.getUserId(request);
        if (StringUtils.isBlank(sId))
            return new UniversalResult<>(UniversalResult.UNLOGIN, "登录信息失效，请重新登陆");
        List<Map<String, Object>> ASList = applySupportMapper.selectListBy(MapUtils.setSelectStatement("BSId,SId,status,date,reason", "SId=" + sId));
        if (ASList.size() == 0)
            return new UniversalResult<>(UniversalResult.GETNULL, "空空如也");
        else
            return new UniversalResult<>(UniversalResult.SUCCESS, "查询成功", ASList);
    }
}
